package ex.com.jm.food.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import ex.com.jm.food.dao.UserEvalDao;
import ex.com.jm.food.entity.Evaluation;

public class UserEvalDaoImpl extends HibernateDaoSupport implements UserEvalDao {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<Evaluation> getEvals(final String menuId,final int initPage,final int pageRow) {
		// TODO Auto-generated method stub
		Object evals=this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				String hql="select new ex.com.jm.food.entity.dto.EvlaDTO("
						+ "eval.evalId,"
						+ "eval.evalStar,eval.evalComment,eval.evalDate,menu.menuName,user.userName"
						+ ") from Evaluation eval left join eval.userId as user "
						+ "left join eval.menuId as menu where eval.comId='"+menuId+"'";
				Query query=session.createQuery(hql).setFirstResult(initPage).setMaxResults(pageRow);
				return query.list();
			}
		});
		return (List<Evaluation>) evals;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public int evalCount(final String menuId) {
		// TODO Auto-generated method stub
		int count=this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				String hql="from Evaluation where menuId='"+menuId+"'";
				Query query=session.createQuery(hql);
				return query.list().size();
			}
		});
		return count;
	}

	@Override
	public Object saveEval(Evaluation evaluation) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().save(evaluation);
	}

}
